package com.example.mybaiduweishi.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mybaiduweishi.MyApplication;
import com.example.mybaiduweishi.R;
import com.example.mybaiduweishi.activity.InsertContactsActivity;
import com.example.mybaiduweishi.activity.OneKeySOSActivity;
import com.example.mybaiduweishi.fragments.base.BaseFragmentbase;
import com.example.mybaiduweishi.utils.ToastUtil;
import com.example.mybaiduweishi.vo.Contacts;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class secondFragment extends BaseFragmentbase {

    @BindView(R.id.edit_insert_sos)
    EditText edit;
    @BindView(R.id.check_one_sos)
    CheckBox check;
    @BindView(R.id.img_insert_sos)
    ImageView imgInsertSos;
    @BindView(R.id.btn_insert_sos)
    Button btnInsertSos;
    @BindView(R.id.btn_yes_second)
    Button btnYesSecond;
    @BindView(R.id.second_recyclerview)
    RecyclerView recyclerview;
    final List<Contacts> listSos = MyApplication.getSoslist();
    final MyRecycleViewAdapter myRecycleViewAdapter = new MyRecycleViewAdapter(listSos);
    Unbinder unbinder;


    @Override
    public int getXML() {
        return R.layout.second_fragment;
    }

    @Override
    public void initView() {
        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (s.length() > 0) {
                    imgInsertSos.setVisibility(View.GONE);
                    btnInsertSos.setVisibility(View.VISIBLE);
                } else {
                    btnInsertSos.setVisibility(View.GONE);
                    imgInsertSos.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void initData() {

    }


    @OnClick({R.id.img_insert_sos, R.id.btn_insert_sos, R.id.btn_yes_second})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_insert_sos:
                //添加联系人
                Intent intent = new Intent(getActivity(), InsertContactsActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_insert_sos:
                //添加联系人之后的确定
                saveEdit();

                break;
            case R.id.edit_insert_sos:

                break;
            case R.id.btn_yes_second:
                //完成这个页面,跳转第三个fragment
                if (MyApplication.getSoslist().size() > 0 &&  check.isChecked() ) {
                    if (getActivity() instanceof OneKeySOSActivity) {
                        ((OneKeySOSActivity) getActivity()).toThirdFragment();
                    }
                }else {
                    Toast.makeText(MyApplication.getContext(), "勾选一键求救和获取联系人", Toast.LENGTH_SHORT).show();
                }
                break;

        }
    }


    private void saveEdit() {

        /**
         * 中国电信号码格式验证 手机段： 133,153,180,181,189,177,1700,173
         * **/
        final String CHINA_TELECOM_PATTERN = "(^1(33|53|7[37]|8[019])\\d{8}$)|(^1700\\d{7}$)";

        /**
         * 中国联通号码格式验证 手机段：130,131,132,155,156,185,186,145,176,1707,1708,1709
         * **/
        final String CHINA_UNICOM_PATTERN = "(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^170[7-9]\\d{7}$)";

        /**
         * 中国移动号码格式验证
         * 手机段：134,135,136,137,138,139,150,151,152,157,158,159,182,183,184
         * ,187,188,147,178,1705
         *
         **/
        final String CHINA_MOBILE_PATTERN = "(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";

        /**
         * 仅手机号格式校验
         */
        final String PHONE_PATTERN = new StringBuilder(300).append(CHINA_MOBILE_PATTERN)
                .append("|")
                .append(CHINA_TELECOM_PATTERN)
                .append("|")
                .append(CHINA_UNICOM_PATTERN)
                .toString();
        Pattern pattern = Pattern.compile(PHONE_PATTERN);
        Matcher matcher = pattern.matcher(edit.getText());
        String tel = edit.getText().toString().trim();
        if (matcher.find()) {
            edit.setText("");
            imgInsertSos.setVisibility(View.VISIBLE);
            btnInsertSos.setVisibility(View.GONE);
            //提交数据到RecycleView
            ToastUtil.showShortToast(MyApplication.getContext(), "添加成功");
            Contacts contacts = new Contacts();
            contacts.setTelnumber(tel);
            if (listSos.size() < 3) {
                listSos.add(contacts);
            } else {
                ToastUtil.showShortToast(getActivity(), "不能超过三人");
            }
            //侧滑删除
            ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
                @Override
                public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                    //首先回调的方法 返回int表示是否监听该方向
//                int dragFlags = ItemTouchHelper.UP|ItemTouchHelper.DOWN;//拖拽
                    int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;//侧滑删除
                    int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;//拖拽  
//                int swipeFlags = 0;//侧滑删除
                    return makeMovementFlags(dragFlags, swipeFlags);
                }

                @Override
                public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                    //滑动事件
                    Collections.swap(listSos, viewHolder.getAdapterPosition(), target.getAdapterPosition());
                    myRecycleViewAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
                    return true;
                }

                @Override
                public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                    //侧滑事件
                    listSos.remove(viewHolder.getAdapterPosition());
                    myRecycleViewAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
                    ToastUtil.showShortToast(MyApplication.getContext(), "删除成功");
                }

                @Override
                public boolean isLongPressDragEnabled() {
                    //是否可拖拽
                    return true;
                }
            });
            helper.attachToRecyclerView(recyclerview);
            recyclerview.setLayoutManager(new LinearLayoutManager(MyApplication.getContext()));
            recyclerview.setAdapter(myRecycleViewAdapter);

        } else {
//            edit.setText("");
            Toast.makeText(MyApplication.getContext(), "输入的手机号码不正确", Toast.LENGTH_SHORT).show();
        }


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    class MyRecycleViewAdapter extends RecyclerView.Adapter<MyRecycleViewAdapter.MyViewHolder> {
        List<Contacts> list = new ArrayList<>();

        public MyRecycleViewAdapter(List<Contacts> list) {
            this.list = list;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.sos_contact_item, parent, false);
            MyViewHolder holder = new MyViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            Contacts contacts = list.get(position);
            holder.name.setText(contacts.getName());
            holder.tel.setText(contacts.getTelnumber());
            holder.address.setText(contacts.getAddress());
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView name;
            TextView tel;
            TextView address;

            public MyViewHolder(View itemView) {
                super(itemView);
                name = (TextView) itemView.findViewById(R.id.tv_sos_name);
                tel = (TextView) itemView.findViewById(R.id.tv_sos_tel);
                address = (TextView) itemView.findViewById(R.id.tv_sos_address);
            }
        }
    }

    /**
     * 碎片一出现就调用
     */
    @Override
    public void onResume() {
        super.onResume();
        if (myRecycleViewAdapter != null) {
            myRecycleViewAdapter.notifyDataSetChanged();
        }
    }
}
